<template>
  <div class="app-container">
    <!-- 搜索和筛选区域 -->
    <el-card class="filter-container" shadow="never">
      <el-form :inline="true" :model="searchForm" ref="searchFormRef" size="small">
        <el-form-item label="姓名">
          <el-input v-model="searchForm.name" placeholder="请输入医生姓名" clearable @keyup.enter="handleSearch" />
        </el-form-item>
        <el-form-item label="科室">
          <el-select v-model="searchForm.departmentId" placeholder="请选择科室" clearable>
            <el-option
              v-for="dept in departments"
              :key="dept.departmentId || dept.id || index"
              :label="dept.name"
              :value="dept.departmentId || dept.id || String(index)"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="职称">
          <el-select v-model="searchForm.title" placeholder="请选择职称" clearable>
            <el-option label="主任医师" value="主任医师" />
            <el-option label="副主任医师" value="副主任医师" />
            <el-option label="主治医师" value="主治医师" />
            <el-option label="住院医师" value="住院医师" />
            <el-option label="医师" value="医师" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="在职" value="在职" />
            <el-option label="离职" value="离职" />
            <el-option label="停诊" value="停诊" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
          <el-button 
            type="success" 
            v-permission="'doctor:create'"
            @click="handleCreate"
          >
            <el-icon><Plus /></el-icon>新增医生
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 表格区域 -->
    <el-card shadow="never" class="table-container">
      <el-table
        v-loading="loading"
        :data="tableData"
        style="width: 100%"
        border
        row-key="userId"
        stripe
      >
        <el-table-column prop="staffId" label="工号" min-width="100" />
        <el-table-column prop="name" label="姓名" min-width="100" />
        <el-table-column prop="gender" label="性别" width="80" />
        <el-table-column prop="title" label="职称" min-width="120" />
        <el-table-column label="科室" min-width="120">
          <template #default="scope">
            <span>{{ getDepartmentName(scope.row.departmentId) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="专长" min-width="200">
          <template #default="scope">
            <el-tag
              v-for="(specialty, index) in scope.row.specialties"
              :key="index"
              class="tag-item"
              type="info"
              effect="light"
            >
              {{ specialty }}
            </el-tag>
            <span v-if="!scope.row.specialties || scope.row.specialties.length === 0">--</span>
          </template>
        </el-table-column>
        <el-table-column label="联系方式" min-width="120">
          <template #default="scope">
            <span>{{ scope.row.contactInfo?.phone || '--' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ scope.row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="220" fixed="right">
          <template #default="scope">
            <el-button 
              type="primary" 
              size="small"
              @click="handleView(scope.row)"
              v-permission="'doctor:read'"
            >
              查看
            </el-button>
            <el-button 
              type="warning" 
              size="small"
              @click="handleEdit(scope.row)"
              v-permission="'doctor:update'"
            >
              编辑
            </el-button>
            <el-button 
              type="danger" 
              size="small"
              @click="handleDelete(scope.row)"
              v-permission="'doctor:delete'"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页控件 -->
      <div class="pagination-container">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { doctorAPI, departmentAPI } from '@/utils/api'

// 路由实例
const router = useRouter()

// 数据加载状态
const loading = ref(false)

// 表格数据
const tableData = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)

// 科室列表
const departments = ref([])

// 搜索表单
const searchFormRef = ref(null)
const searchForm = reactive({
  name: '',
  departmentId: '',
  title: '',
  status: ''
})

// 根据状态获取标签类型
const getStatusType = (status) => {
  const statusMap = {
    '在职': 'success',
    '离职': 'info',
    '停诊': 'warning'
  }
  return statusMap[status] || 'info'
}

// 获取科室名称
const getDepartmentName = (departmentId) => {
  if (!departmentId) return '--'
  // 先尝试在departments列表中查找
  const dept = departments.value.find(d => d.departmentId === departmentId || d.id === departmentId)
  if (dept) return dept.name
  
  // 如果在列表中找不到，使用一些内置的映射
  const deptMap = {
    '682c55b57d196017f623bcf0': '内科',
    '682c55b57d196017f623bcf1': '外科',
    '682c55b57d196017f623bcf2': '儿科',
    '682c55b57d196017f623bcf3': '妇产科',
    '682c55b57d196017f623bcf4': '眼科',
    '682c55b57d196017f623bcf5': '口腔科'
  }
  
  return deptMap[departmentId] || '--'
}

// 获取科室列表
const getDepartments = async () => {
  try {
    const res = await departmentAPI.getDepartments()
    // 检查返回数据格式并使用正确的字段
    if (res.success && res.data) {
      let tempDepartments = [];
      
      // 尝试获取不同格式的科室列表数据
      if (Array.isArray(res.data.departments)) {
        tempDepartments = res.data.departments;
      } else if (Array.isArray(res.data.items)) {
        tempDepartments = res.data.items;
      } else if (Array.isArray(res.data)) {
        tempDepartments = res.data;
      } else {
        // 如果没有数据，创建一些默认的科室数据
        tempDepartments = [
          { departmentId: '1', id: '1', name: '内科' },
          { departmentId: '2', id: '2', name: '外科' },
          { departmentId: '3', id: '3', name: '儿科' },
          { departmentId: '4', id: '4', name: '妇产科' },
          { departmentId: '5', id: '5', name: '眼科' },
          { departmentId: '6', id: '6', name: '口腔科' }
        ];
      }
      
      // 确保每个科室对象都有有效的ID属性
      departments.value = tempDepartments.map((dept, index) => {
        // 确保每个科室都有departmentId或id属性
        if (!dept.departmentId && !dept.id) {
          dept.departmentId = String(index + 1);
        }
        return dept;
      });
      
      console.log('获取到科室数据:', departments.value.length, '条记录');
    } else {
      console.error('获取科室列表数据格式异常:', res)
      // 设置默认科室数据
      departments.value = [
        { departmentId: '1', id: '1', name: '内科' },
        { departmentId: '2', id: '2', name: '外科' },
        { departmentId: '3', id: '3', name: '儿科' },
        { departmentId: '4', id: '4', name: '妇产科' },
        { departmentId: '5', id: '5', name: '眼科' },
        { departmentId: '6', id: '6', name: '口腔科' }
      ]
    }
  } catch (error) {
    console.error('获取科室列表失败', error)
    ElMessage.error('获取科室列表失败')
    // 设置默认科室数据
    departments.value = [
      { departmentId: '1', id: '1', name: '内科' },
      { departmentId: '2', id: '2', name: '外科' },
      { departmentId: '3', id: '3', name: '儿科' },
      { departmentId: '4', id: '4', name: '妇产科' },
      { departmentId: '5', id: '5', name: '眼科' },
      { departmentId: '6', id: '6', name: '口腔科' }
    ]
  }
}

// 获取医生列表
const getDoctors = async () => {
  loading.value = true
  try {
    // 构建查询参数
    const params = {
      page: currentPage.value,
      limit: pageSize.value,
      ...searchForm
    }
    
    // 移除空字段
    Object.keys(params).forEach(key => {
      if (params[key] === '' || params[key] === null || params[key] === undefined) {
        delete params[key]
      }
    })
    
    const res = await doctorAPI.getDoctors(params)
    
    // 修复这里 - 使用正确的数据字段名称
    if (res.success && res.data) {
      // 使用doctors而不是items
      tableData.value = res.data.doctors || []
      total.value = res.data.total || 0
      
      // 调试输出
      console.log('获取到医生数据:', tableData.value.length, '条记录')
    } else {
      console.error('后端返回格式异常:', res)
      tableData.value = []
      total.value = 0
    }
  } catch (error) {
    console.error('获取医生列表失败', error)
    ElMessage.error('获取医生列表失败')
    tableData.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

// 搜索方法
const handleSearch = () => {
  currentPage.value = 1
  getDoctors()
}

// 重置搜索
const resetSearch = () => {
  searchFormRef.value.resetFields()
  currentPage.value = 1
  getDoctors()
}

// 页码变化
const handleCurrentChange = (val) => {
  currentPage.value = val
  getDoctors()
}

// 每页条数变化
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
  getDoctors()
}

// 新增医生
const handleCreate = () => {
  router.push('/doctors/create')
}

// 查看医生详情
const handleView = (row) => {
  // 使用id或userId作为路由参数
  const doctorId = row.id || row.userId
  if (!doctorId) {
    ElMessage.error('医生ID不存在，无法查看详情')
    return
  }
  console.log('查看医生详情，ID:', doctorId)
  router.push(`/doctors/detail/${doctorId}`)
}

// 编辑医生
const handleEdit = (row) => {
  // 优先使用id字段，其次是_id，最后才使用userId
  const doctorId = row.id || row._id || row.userId;
  if (!doctorId) {
    ElMessage.error('医生ID不存在，无法编辑');
    return;
  }
  console.log('编辑医生，使用ID:', doctorId);
  router.push(`/doctors/edit/${doctorId}`);
}

// 删除医生
const handleDelete = (row) => {
  // 优先使用id字段，其次是_id，最后才使用userId
  const doctorId = row.id || row._id || row.userId;
  if (!doctorId) {
    ElMessage.error('医生ID不存在，无法删除');
    return;
  }
  
  ElMessageBox.confirm(
    `确定要删除医生 ${row.name} 吗？`,
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
    try {
      await doctorAPI.deleteDoctor(doctorId)
      ElMessage.success('删除成功')
      getDoctors()
    } catch (error) {
      console.error('删除失败', error)
      ElMessage.error('删除失败')
    }
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

// 页面加载时获取数据
onMounted(() => {
  getDepartments()
  getDoctors()
})
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.filter-container {
  margin-bottom: 20px;
}

.filter-container .el-form {
  display: flex;
  flex-wrap: wrap;
}

.table-container {
  margin-bottom: 20px;
}

.tag-item {
  margin-right: 4px;
  margin-bottom: 4px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

/* 响应式调整 */
@media screen and (max-width: 768px) {
  .filter-container .el-form-item {
    margin-right: 0;
    width: 100%;
  }
}
</style> 